package com.wwtech.epp.ui.activity.work;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.Comment;
import com.wwtech.epp.entity.ProjectDetail;
import com.wwtech.epp.entity.TaskDetail;
import com.wwtech.epp.entity.eventbus.DeletProject;
import com.wwtech.epp.entity.eventbus.FinishProject;
import com.wwtech.epp.entity.eventbus.TaskChange;
import com.wwtech.epp.ui.activity.work.component.DaggerProjectDetailComponent;
import com.wwtech.epp.ui.activity.work.contract.ProjectDetailContract;
import com.wwtech.epp.ui.activity.work.module.ProjectDetailModule;
import com.wwtech.epp.ui.activity.work.presenter.ProjectDetailPresenter;
import com.wwtech.epp.ui.adapter.work.CommentListAdapter;
import com.wwtech.epp.ui.adapter.work.ProjectDetailProjectTaskAdapter;
import com.wwtech.epp.ui.adapter.work.ReportListAdapter;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.utils.WorkUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/09/15 15:02:18
 */

public class ProjectDetailActivity extends BaseActivity implements ProjectDetailContract.View {

    @Inject
    ProjectDetailPresenter mPresenter;

    @Inject
    ReportListAdapter reportListAdapter;
    @Inject
    CommentListAdapter commentListAdapter;

    @BindView(R.id.tv_project_name)
    TextView tvProjectName;
    @BindView(R.id.tv_project_status)
    TextView tvProjectStatus;
    @BindView(R.id.tv_project_id)
    TextView tvProjectId;
    @BindView(R.id.tv_project_target)
    TextView tvProjectTarget;
    @BindView(R.id.tv_project_desc)
    TextView tvProjectDesc;
    @BindView(R.id.tv_project_manager)
    TextView tvProjectManager;
    @BindView(R.id.tv_project_part)
    TextView tvProjectPart;
    @BindView(R.id.tv_project_start_time)
    TextView tvProjectStartTime;
    @BindView(R.id.tv_project_end_time)
    TextView tvProjectEndTime;
    @BindView(R.id.recycerView_task)
    RecyclerView recycerViewTask;
    @BindView(R.id.recycerView_project_report)
    RecyclerView recycerViewProjectReport;
    @BindView(R.id.recycerView_project_comment)
    RecyclerView recycerViewProjectComment;
    @BindView(R.id.tv_ccomment)
    TextView tvCcomment;
    @BindView(R.id.star)
    TextView star;
    @BindView(R.id.report)
    TextView report;
    @BindView(R.id.finish)
    TextView finish;

    @BindView(R.id.mask)
    View mask;

    @BindView(R.id.no_comment_desc)
    TextView noCommentDesc;
    @BindView(R.id.no_report_desc)
    TextView noReportDesc;

    @BindView(R.id.no_task_desc)
    TextView noTaskDesc;

    private ProjectDetailProjectTaskAdapter projectDetailProjectTaskAdapter;
    private int projectId;
    private String projectName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_project_detail);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        recycerViewTask.setNestedScrollingEnabled(false);
        recycerViewProjectReport.setNestedScrollingEnabled(false);
        recycerViewProjectReport.setAdapter(reportListAdapter);
        recycerViewProjectComment.setNestedScrollingEnabled(false);
        recycerViewProjectComment.setAdapter(commentListAdapter);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void initData() {
        setTitle("项目详情");
        Map<String, String> map = new HashMap<>();
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        mPresenter.getProjectDetail(getIntent().getIntExtra("projectId", -1) + "", map);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskStateChange(TaskChange taskChange) {
        if (projectDetailProjectTaskAdapter.getData().size() != 0) {
            noTaskDesc.setVisibility(View.GONE);
        }
        for (TaskDetail data : projectDetailProjectTaskAdapter.getData()) {
            if (data.getJobId() == taskChange.taskId) {
                data.setJobState(taskChange.taskState);
                projectDetailProjectTaskAdapter.notifyDataSetChanged();
                return;
            }
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddReport(String content) {
        KLog.i("哈哈哈哈哈哈或或");
        if (content.equals("add")) {
            initData();
        }
        if (content.equals("addComment")) {
            Map<String, String> commentMap = new HashMap<>();
            commentMap.put("pageNum", "1");
            commentMap.put("pageSize", "100");
            mPresenter.getProjectComment(projectId + "", commentMap);
        }
    }

    @Override
    protected void setupActivityComponent() {
        DaggerProjectDetailComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .projectDetailModule(new ProjectDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(ProjectDetailContract.ProjectDetailContractPresenter presenter) {
        mPresenter = (ProjectDetailPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void showProject(ProjectDetail projectDetail) {
        projectId = projectDetail.getData().getProjectId();
        projectName = projectDetail.getData().getProjectName();
        tvProjectName.setText(projectName);
        tvProjectTarget.setText(projectDetail.getData().getProjectTarget());
        tvProjectDesc.setText(projectDetail.getData().getProjectDesc());
        tvProjectManager.setText(projectDetail.getData().getNickName());
        String partPerson = "";
        for(int i = 0; i < projectDetail.getData().getJoiner().size(); i++) {
            partPerson += projectDetail.getData().getJoiner().get(i).getNickName() + "  ";
        }
        tvProjectPart.setText(partPerson);
        tvProjectId.setText(projectDetail.getData().getProjectId() + "");
        tvProjectStartTime.setText(projectDetail.getData().getBeginTime().substring(0, 10));
        tvProjectEndTime.setText(projectDetail.getData().getEndTime().substring(0, 10));
        if (projectDetail.getData().getReports().size() != 0) {
            noReportDesc.setVisibility(View.GONE);
        }
        reportListAdapter.setNewData(projectDetail.getData().getReports());
        reportListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent = new Intent(ProjectDetailActivity.this, ReportDetailActivity.class);
                intent.putExtra("projectName", projectDetail.getData().getProjectName());
                intent.putExtra("dataBean", reportListAdapter.getData().get(i));
                startActivity(intent);
            }
        });

        projectDetailProjectTaskAdapter = new ProjectDetailProjectTaskAdapter(projectDetail.getData().getSubJob());
        if (projectDetailProjectTaskAdapter.getData().size() != 0) {
            noTaskDesc.setVisibility(View.GONE);
        }
        projectDetailProjectTaskAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent = new Intent(ProjectDetailActivity.this, TaskDetailActivity.class);
                intent.putExtra("dataBean", projectDetailProjectTaskAdapter.getData().get(i));
                startActivity(intent);
            }
        });
        commentListAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (commentListAdapter.getData().get(i).getUserId() == ContainValue.userLogin.getData().getUserId()) {
                    showDeletCommentDialog(i);
                }
                return true;
            }
        });
        recycerViewTask.setAdapter(projectDetailProjectTaskAdapter);
        mask.setVisibility(View.GONE);
        star.setText(projectDetail.getData().isStar()? "已加星标" : "加星标");
        if (ContainValue.userLogin.getData().getRoleLevel() == 0) {
            report.setVisibility(View.VISIBLE);
            tvCcomment.setText("评论");
        } else {
            report.setVisibility(View.GONE);
            if (ContainValue.userLogin.getData().getRoleLevel() == 1) {
                tvCcomment.setText("建议");
            }
            if (ContainValue.userLogin.getData().getRoleLevel() == 2) {
                tvCcomment.setText("批示");
            }
            if (ContainValue.userLogin.getData().getRoleLevel() == 3) {
                tvCcomment.setText("批示");
            }
        }
        Map<String, String> commentMap = new HashMap<>();
        commentMap.put("pageNum", "1");
        commentMap.put("pageSize", "100");
        mPresenter.getProjectComment(projectId + "", commentMap);
        if (WorkUtil.isUnValuableTask(projectDetail.getData().getEndTime()) == -1 || projectDetail.getData().getProjectState() == 1 || WorkUtil.isUnValuableTask(projectDetail.getData().getEndTime()) == 0) {
            switch (projectDetail.getData().getProjectState()) {
                case 0:
                    tvProjectStatus.setText("进度正常");
                    tvProjectStatus.setTextColor(getResources().getColor(R.color.main_color));
                    break;
                case 1:
                    tvProjectStatus.setText("已结束");
                    tvProjectStatus.setTextColor(getResources().getColor(R.color.color_finish_task));
                    finish.setText("已经完成");
                    finish.setClickable(false);
                    break;
                default:
                    break;
            }
        } else {
            tvProjectStatus.setText("超期" + WorkUtil.isUnValuableTask(projectDetail.getData().getEndTime()) + "天");
            tvProjectStatus.setTextColor(getResources().getColor(R.color.color_f51818));
            finish.setText("完成");
        }
        if (projectDetail.getData().getOwnerUid() != ContainValue.userLogin.getData().getUserId()) {
            toolbar.getMenu().clear();
            finish.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAddStarBack(boolean addStar) {
        if (addStar) {
            ToastUtil.displayShortToast("加星标成功");
            star.setText("已加星标");
        } else {
            ToastUtil.displayShortToast("取消星标成功");
            star.setText("加星标");
        }
    }

    @Override
    public void onQuickSuccess() {
        Map<String, String> map = new HashMap<>();
        map.put("projectId", projectId + "");
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        mPresenter.quickProject(map);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.delet_project_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delet_project:
                showDeletProjectDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showDeletProjectDialog() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        View view1 = View.inflate(this, R.layout.two_choose_dialog, null);
        alertDialog.setView(view1);
        alertDialog.setCancelable(true);
        TextView tv_title = (TextView) view1.findViewById(R.id.content);
        tv_title.setText("删除该项目？");
        TextView cancal = (TextView) view1.findViewById(R.id.cancal);
        TextView sure = (TextView) view1.findViewById(R.id.sure);
        cancal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<>();
                map.put("projectId", projectId + "");
                map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                mPresenter.deletProject(map);
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    @Override
    public void onFinishProjectSuccess() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        mPresenter.getProjectDetail(getIntent().getIntExtra("projectId", -1) + "", map);
        EventBus.getDefault().post(new FinishProject(projectId, 0));
    }

    @Override
    public void showProjectComment(Comment comment) {
        commentListAdapter.setNewData(comment.getData().getList());
        if (commentListAdapter.getData().size() != 0) {
            noCommentDesc.setVisibility(View.GONE);
        }
    }

    @Override
    public void deletSuccess() {
        EventBus.getDefault().post(new DeletProject(projectId, 0));
        ToastUtil.displayShortToast("删除项目成功");
        finish();
    }

    @Override
    public void deletCommentSuccess() {
        ;Map<String, String> commentMap = new HashMap<>();
        commentMap.put("pageNum", "1");
        commentMap.put("pageSize", "100");
        mPresenter.getProjectComment(projectId + "", commentMap);
    }

    private void showDeletCommentDialog(int postion) {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        View view1 = View.inflate(this, R.layout.two_choose_dialog, null);
        alertDialog.setView(view1);
        alertDialog.setCancelable(true);
        TextView tv_title = (TextView) view1.findViewById(R.id.content);
        tv_title.setText("删除该条评论？");
        TextView cancal = (TextView) view1.findViewById(R.id.cancal);
        TextView sure = (TextView) view1.findViewById(R.id.sure);
        cancal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("commentId", commentListAdapter.getData().get(postion).getCommentId() + "");
                mPresenter.deletComment(commentListAdapter.getData().get(postion).getCommentId() + "", map);
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    @OnClick({R.id.tv_ccomment, R.id.star, R.id.report, R.id.finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ccomment:
                Intent intent1 = new Intent(ProjectDetailActivity.this, AddCommentActivity.class);
                intent1.putExtra("projectId", projectId + "");
                intent1.putExtra("flag", tvCcomment.getText());
                startActivity(intent1);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                break;
            case R.id.star:
                Map<String, String> map = new HashMap<>();
                map.put("projectId", getIntent().getIntExtra("projectId", -1) + "");
                map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                mPresenter.addStar(map);
                break;
            case R.id.report:
                Intent intent = new Intent(ProjectDetailActivity.this, ProjectReportActivity.class);
                intent.putExtra("title", "");
                intent.putExtra("projectId", projectId + "");
                intent.putExtra("projectName", projectName);
                startActivity(intent);
                break;
            case R.id.finish:
                Map<String, String> map2 = new HashMap<>();
                map2.put("projectId", projectId + "");
                map2.put("userId", ContainValue.userLogin.getData().getUserId() + "");
                mPresenter.finishProject(map2);
                break;
            default:
                break;
        }
    }
}